import base64
import hashlib
import hmac
import json
import sys
import time
import urllib

import requests


def send_to_ding(text):
    url = 'https://oapi.dingtalk.com/robot/send?access_token=505f6881ef86b6d438d9f96d851bce677c8110038e5e8d230657aab792fcce5f'
    timestamp = str(round(time.time() * 1000))
    secret = 'SECcf3cb7b436a0b2a2f184f1af7774456540cb35beaeed6e958c22f9a5a83e9a79'
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    # print(timestamp)
    # print(sign)
    url = url + '&timestamp=' + timestamp + '&sign=' + sign
    print(url)
    data = {'msgtype': 'text',
            'text': {
                'content': text
            },
            'at': {
                "atMobiles": [
                ],
                "isAtAll": False
            }
            }
    print(data)
    headers = {'Content-Type': 'application/json', }
    r = requests.post(url, data=json.dumps(data), headers=headers)
    res = json.loads(r.text)
    print(res)


text = sys.argv[1]
send_to_ding(text)
